package cn.findviewbydream.service.impl;

import cn.findviewbydream.dao.LoginDAO;
import cn.findviewbydream.entity.UserEntity;
import cn.findviewbydream.enums.LoginEnum;
import cn.findviewbydream.exception.LoginException;
import cn.findviewbydream.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**********************************
 * 工程：who
 * 作者：白雨濃 evil
 * 时间：2017/4/9 14:38
 * 邮箱：evilbai@foxmail.com
 * 内容：
 *********************************/
@Service
public class LoginServiceImpl implements LoginService
{
    private final LoginDAO dao;

    @Autowired
    public LoginServiceImpl(LoginDAO dao)
    {
        this.dao = dao;
    }

    @Override
    public UserEntity login(String userId, String password)
    {
        UserEntity entity = dao.selectUser(userId);
        if (entity == null)
            throw new LoginException(LoginEnum.NO_USER);

        if(!entity.getPassword().equals(password))
            throw new LoginException(LoginEnum.ERROR_PASSWORD);

        return entity;
    }

    @Override
    public UserEntity getUser(String userId, HttpSession session) throws Exception
    {
        UserEntity entity = (UserEntity) session.getAttribute("user");
        if (entity == null || !entity.getUserId().equals(userId))
            throw new LoginException(LoginEnum.NO_LOGIN);

        return new UserEntity("id", "password", "name", "img", 0);
    }
}
